# Author:Christina
# -*- codeing = utf-8 -*-
# @Time : 2021/7/31 22:24
# @Author : 19838
# @File : .py
# @Software: PyCharm

from bs4 import BeautifulSoup  # 网页解析，获取数据
import re  # 正则表达式，进行文字匹配
import urllib.request, urllib.error  # 制定URL，获取网页数据
import xlwt  # 进行excel操作

'''
**爬取猪八戒服务平台**
https://beijing.zbj.com/
https://beijing.zbj.com/channel/brand
爬取店铺信息，你能获取什么就获取什么
提示：也很常规，自己训练使用xpath，正则，css选择器
'''


def main():
    baseurl = "https://beijing.zbj.com/channel/brand"
    savepath = "猪八戒店铺.xls"
    # 1.爬取网页
    datalist = getData(baseurl)
    # 3.保存数据
    saveData(datalist, savepath)


findShopTitle = re.compile(r'<div class="shop-title">(.*)</div>')
findEmployers = re.compile(r'<span><label>近半年已服务雇主：</label>(\d*)家</span>')
findImgSrc = re.compile(r'<img class="shop-avatar" src="(.*?)">', re.S)
findTurnover = re.compile(r'<span><label>近半年成交额：</label>(\d*)万</span>')
findCapital = re.compile(r'<span><label>注册资本：</label>(\d*)万</span>')
findTime = re.compile(r'<span><label>成立时间：</label>(.*)</span>')
findComment = re.compile(r'<span class="comment-desc">雇主评论：(.*?)</span>', re.S)
findSpecialty = re.compile(r'<div class="shop-expert"><span class="expert-title">擅长：</span>(.*)</div>', re.S)
findRating = re.compile(r'<span class="comment-title"><i></i>(\d*%)好评率</span>')


# 爬取网页
def getData(baseurl):
    datalist = []
    html = askURL(baseurl)  # 保存获取到的网页源码
    # 2.逐一解析数据
    soup = BeautifulSoup(html, "html.parser")
    for item in soup.find_all('div', class_="brand-content"):  # 查找符合要求的字符串,class是一个类别加下划线
        # print(item)   #测试
        data = []
        item = str(item)

        shopTitle = re.findall(findShopTitle, item)  # re库用来通过正则表达式查找指定的字符串
        data.append(shopTitle)

        imgSrc = re.findall(findImgSrc, item)
        data.append(imgSrc)

        rating = re.findall(findRating, item)
        data.append(rating)

        employersNum = re.findall(findEmployers, item)
        data.append(employersNum)

        time = re.findall(findTime, item)
        data.append(time)

        capital = re.findall(findCapital, item)
        data.append(capital)

        turnover = re.findall(findTurnover, item)
        data.append(turnover)

        specialty = re.findall(findSpecialty, item)
        # print("擅长：", specialty)    #测试
        if len(specialty) != 0:
            specialty = specialty.sub('<span(\s+)?/(\s+)?>', " ", specialty)  # 去掉句号
            data.append(specialty.strip())
        else:
            data.append("无")  # 留空

        comment = re.findall(findComment, item)[0]
        comment = re.sub('<br(\s+)?/>(\s+)?', " ", comment)  # 去掉<br/>
        # comment = re.sub('/', " ", comment)  # 替换/
        data.append(comment.strip())  # 去掉前后的空格

        datalist.append(data)
    print ("datalist是：",datalist)
    return datalist


# 得到指定一个url的网页内容
def askURL(url):
    head = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 SLBrowser/7.0.0.6241 SLBChan/30"
    }
    request = urllib.request.Request(url, headers=head)
    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode("utf-8")  # 读取解码
        # print(html)
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    return html


# 保存数据
def saveData(datalist, savepath):
    # print("save....")
    book = xlwt.Workbook(encoding="utf-8", style_compression=0)  # 创建workbook对象
    sheet = book.add_sheet('猪八戒店铺', cell_overwrite_ok=True)  # 创建工作表
    col = ("店铺名","logo链接","好评率","近半年已服务雇主","成立时间","注册资本","近半年成交额","擅长","雇主评论")
    for i in range(0, 9):
        sheet.write(0, i, col[i])  # 列名
    for i in range(0, 100):
        print("第%d条" % (i + 1))  # ????
        data = datalist[i]
        for j in range(0, 9):
            sheet.write(i + 1, j, data[j])  # 数据

    book.save(savepath)  # 保存


if __name__ == '__main__':
    main()
    print("爬取完毕！")
